﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TWS.Cart.Data;

public partial class Application_Controls_SignUp : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

	protected void CheckBoxCopyAddress_Changed(object sender, EventArgs e)
	{
		if (CheckBoxCopyAddress.Checked)
			AddressBuiling.CopyValuesFromAddressControl(AddressShipping);
		else
			AddressBuiling.Clear();
	} 	

	public void ButtonCheckoutNewCustomer_Click(object sender, EventArgs e)
	{
		//Importat rule must check for existing email user.
		UserCollection ssUsers = new UserCollection()
		.Where(User.Columns.Email, TextBoxEmail.Text)
			.Load();


		if (ssUsers.Count > 0) //This email already exists.
		{
			CustomValUserExists.IsValid = false;
		}
		else //no existing user lets add him.
		{
			try
			{
				//Save the User
				var ssUser = new User();
				var ssClient = new CartCatClient();

				ssUser.FullName = TextBoxFullName.Text;
				ssUser.Email = TextBoxEmail.Text;
				ssUser.Password = TextBoxPassword.Text;
				ssUser.Save();

				//Save other details.
				if (string.IsNullOrEmpty(TextBoxTelephone.Text))
				{
					var ssContactInfo = new ContactInformation();
					ssContactInfo.ValueX = TextBoxTelephone.Text;
					ssContactInfo.ContactTypeId = 1;
					ssContactInfo.Save();

					var ssUsersContact = new UsersContactInformation();
					ssUsersContact.UsersId = ssUser.Id;
					ssUsersContact.ContactInformationId = ssContactInfo.Id;
					ssUsersContact.Save();
				}


				//Save the Client
				ssClient.UsersId = ssUser.Id;
				ssClient.Save();

				//Save the addresses
				AddressBuiling.Save(1);
				AddressBuiling.SaveRelationToClient(ssUser.Id);

				AddressShipping.Save(2);
				AddressShipping.SaveRelationToClient(ssUser.Id);

				//If everything went well then 
				//Send to confirmation page.
				var ssConfigParam = new CartCatConfigurationParameter(CartCatConfigurationParameter.Columns.KeyName, "ConfirmUrl");
				Response.Redirect(ssConfigParam.ValueX);

			}
			catch (Exception)
			{

				MessageBoxNewUser.Text = "Error Ocured";
				MessageBoxNewUser.Visible = true;
			}


		}

	}
}
